package com.starrk.myblog.foreground.web;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.starrk.myblog.foreground.entity.TbBlogger;
import com.starrk.myblog.foreground.service.MPTbBloggerService;
import com.starrk.myblog.foreground.vo.LoginVo;
import com.starrk.myblog.foreground.vo.SystemResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Random;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Starrk
 * @since 2018-03-25
 */
@Controller
@RequestMapping("/foreground/tbBlogger")
public class TbBloggerController {

    @Autowired
    private MPTbBloggerService mpTbBloggerService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 通过用户ID获取用户信息
     * @param id
     * @return
     */
    @RequestMapping("/getTbBloggerInfoById")
    public SystemResult getTbBloggerInfo(@RequestParam("bloggerId") Long id){
        TbBlogger blogger;

        try{
            String back =(String)redisTemplate.opsForValue().get("TbBlogger"+id);
            blogger = JSON.parseObject(back,TbBlogger.class);
            if(null==blogger||"".equals(blogger)) blogger = mpTbBloggerService.selectById(id);
            return SystemResult.isOk(blogger);
        }catch (Exception e){
            return SystemResult.build(201,e.getMessage());
        }
    }

  /**
   * 通过用户名和密码查询用户信息
   * @param loginVo
   * @param request
   * @return
   */
    @PostMapping("/signinbyUAP")
    public String getTbBloggerInfo(LoginVo loginVo, HttpServletRequest request){
        System.out.println("登陆时的Vo:"+loginVo);
        UsernamePasswordToken token = new UsernamePasswordToken(loginVo.getUsername(),loginVo.getPassword(),loginVo.isRemenberMe());
        try {
            SecurityUtils.getSubject().login(token);
            System.out.println("SESSION ID =========================================== " + SecurityUtils.getSubject().getSession().getId());
            return "index";
        }catch(Exception e) {
            request.setAttribute("wrongMessage",e.getMessage());
            return "signin.html";
        }

    }

    /**
     * 注册用户
     * @param tbBlogger
     * @return
     */
    @PostMapping("/registTbBlogger")
    @ResponseBody
    public SystemResult addTbBlogger( TbBlogger tbBlogger){
        System.out.println("{========================"+tbBlogger+"============================}");
        try {
            //建表时可以设置为int/double 这样就可以实现每个用户的随机盐值了。
            tbBlogger.setSalt("3");
            // Md5Hash.fromHexString(tbBlogger.getSalt())
            SimpleHash password = new SimpleHash("md5",tbBlogger.getPassword(), ByteSource.Util.bytes(tbBlogger.getSalt()),2);
            tbBlogger.setPassword(password.toString());
            tbBlogger.setGrade("一楼修士");
            tbBlogger.setScore(100);
            tbBlogger.setCreateTime(new Date(System.currentTimeMillis()));
            tbBlogger.setUpdateTime(tbBlogger.getCreateTime());
            mpTbBloggerService.insert(tbBlogger);
            return SystemResult.isOk();
        }catch (Exception e){
            return SystemResult.build(201,e.getMessage());
        }
    }

    @PostMapping("/updateTbBlogger")
    @ResponseBody
    public SystemResult updateTbBlogger(TbBlogger tbBlogger){
        try {
            tbBlogger.setUpdateTime(new Date(System.currentTimeMillis()));
            mpTbBloggerService.updateById(tbBlogger);
            return SystemResult.isOk();
        }catch (Exception e){
            return SystemResult.build(201,e.getMessage());
        }
    }

    @GetMapping("/deleteTbBlogger/{id}")
    @ResponseBody
    public SystemResult deleteTbBogger(@PathVariable("id")Long id){
        try{
            mpTbBloggerService.deleteById(id);
            return SystemResult.isOk();
        }catch (Exception e){
            return SystemResult.build(201,e.getMessage());
        }
    }


//    @RequestMapping("/getUserById/{bloggerId}")
//    @ResponseBody
//    public TbBlogger getUserInfos(ModelMap model,@PathVariable("bloggerId") Long id){
//        TbBlogger blogger = mpTbBloggerService.selectById(id);
//
//
//        return blogger;
//    }


}

